﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Caching;
using System.Web.Hosting;

namespace Lava.Web
{
    public class FileWatcher
    {
        private readonly string _virtualPath;
        private readonly IEnumerable<string> _dependencies;
        private readonly Action<string> _changeCallback;

        private FileWatcher(string virtualPath, IEnumerable<string> dependencies, Action<string> changeCallback)
        {
            _virtualPath = virtualPath;
            _dependencies = dependencies;
            _changeCallback = changeCallback;
        }

        public static void OnChange(string virtualPath, IEnumerable<string> dependencies, Action<string> action)
        {
            var notifier = new FileWatcher(virtualPath, dependencies, action);
            notifier.Listen();
        }

        public void Listen()
        {
            HttpRuntime.Cache.Insert(_virtualPath,
                                     _virtualPath,
                                     HostingEnvironment.VirtualPathProvider.GetCacheDependency(_virtualPath , _dependencies, DateTime.UtcNow),
                                     Cache.NoAbsoluteExpiration,
                                     Cache.NoSlidingExpiration,
                                     CacheItemPriority.NotRemovable,
                                     OnCacheItemRemoved);
        }

        private void OnCacheItemRemoved(string fileName, object value, CacheItemRemovedReason reason)
        {
            Listen();

            if (reason == CacheItemRemovedReason.DependencyChanged)
            {
                _changeCallback(fileName);
            }
        }
    }
}
